package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.base.BaseCanPlayActivity;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.beans.ADynamicsItem;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.AnchorCircleAdapter;
import com.sctvcloud.dongqu.ui.adapter.AnchorHomePageAdapter;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;
import com.sctvcloud.dongqu.ui.widget.BasePlayerView;
import com.sctvcloud.dongqu.utils.ListTypeUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 主播圈
 */
public class AnchorCircleActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.anchor_circle_ll)
    protected ViewGroup title_lay;
    @BindView(R.id.anchor_circle_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.anchor_circle_list)
    protected RecyclerView circle_list;
    //    @BindView(R.id.video_container)
//    protected AbsoluteLayout videoContainer;
    private LinearLayoutManager manager;
    private AnchorCircleAdapter adapter;
    private int currentPage = 0;
    private int pageAll = 0;
    private String cicleUrl;
    private int firCPos;
    private int firstVPos;
    private ADynamicsItem dynamicsTemp;
    private int tempPos;
    private MotionEvent mCurrentMotion;
    private int height;
    private RecyclerView.OnScrollListener scrollListener;

    private BasePlayerView videoPlayers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        isVideoTop = false;
//        circle_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                if (floatVideoUtils != null && floatVideoUtils.isShowing()) {
//                    floatVideoUtils.scrollBy(dx, dy);
//                }
//            }
//        });
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_anchor_circle);
        ButterKnife.bind(this);
    }

    @Override
    protected BasePlayerView initVideoPlayer() {
        if (videoPlayers == null) {
            videoPlayers = new BasePlayerView(this);
        }
        return videoPlayers;
    }

    @Override
    protected StandardGSYVideoPlayer getVideoPlayer() {
        return videoPlayers;
    }

    private void initView() {
        final int pa = getResources().getDimensionPixelOffset(R.dimen.divider_shadow_margin_bottom);
        title_lay.postDelayed(new Runnable() {
            @Override
            public void run() {
                height = title_lay.getHeight() + pa;
            }
        }, 300);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        circle_list.setItemAnimator(new DefaultItemAnimator());
        circle_list.setLayoutManager(manager);
        cicleUrl = getIntent().getStringExtra(EX_HTML);
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            currentPage = currentPage + 1;
            if (currentPage <= pageAll) {
                getDyArray(currentPage);
            }
        }
    }

    @Override
    public void onRefresh() {
        getDyArray(0);

    }

    /**
     * 网络请求主播圈数据
     * @param calledPage
     * @return
     */
    private boolean getDyArray(int calledPage) {
        if (TextUtils.isEmpty(cicleUrl)) {
            toast("数据错误");
            return false;
        }
        NetUtils.getNetAdapter().getDynamicsPage(getOwnerName(), cicleUrl, calledPage
                , new AbsListNetCallback<ADynamicsItem>(ListTypeUtils.ADynamicItem(), calledPage) {
                    @Override
                    public void onSuc(List<ADynamicsItem> aDynamicsItems) {
                        if (ListUtils.isListValued(aDynamicsItems)) {
                            pageAll = getPageResponse().getData().getPageAll();
                            currentPage = getPageResponse().getData().getPageIndex();
                            setDynamicsData(aDynamicsItems);
                        }
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onNetFinish();
                    }
                });
        return true;
    }

    /**
     * 数据请求结束，刷新layout状态
     */
    private void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(currentPage + 1 < pageAll);
    }


    /**
     * 加载主播圈数据列表
     * @param aDynamicsItems
     */
    private void setDynamicsData(List<ADynamicsItem> aDynamicsItems) {
        for (int i = 0; i < aDynamicsItems.size(); i++) {
            ADynamicsItem aDynamicsItem = aDynamicsItems.get(i);
            aDynamicsItem.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
//            aDynamicsItem.setCoverImage("/sctv/1/image/public/201708/20170828112101_pex8ecr7nr.jpg");
//            aDynamicsItem.setContentVideo("http://baobab.wdjcdn.com/1455969783448_5560_854x480.mp4");
        }
        if (currentPage == 0) {
            if (adapter == null) {
                adapter = new AnchorCircleAdapter(this, aDynamicsItems);
                adapter.setPlayClick(playOnItemClick);
                circle_list.setAdapter(adapter);
            } else {
                adapter.setData(aDynamicsItems);
            }
        } else {
            int pos = adapter.getItemCount();
            adapter.addDatas(aDynamicsItems);
            if (pos > 0) {
                adapter.notifyItemChanged(pos - 1);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SkipUtil.REQUEST_CODE_PLAY_BASE) {
            if (refreshLayout.isRefreshing()) {
                return;
            }
            if (data != null) {
                int itemPos = data.getIntExtra(SkipUtil.EX_POS_ITEM, -1);
                if (itemPos >= 0) {
                    ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(itemPos);
                    if (dynamics == null) {
                        return;
                    }
                    if (resultCode == RESULT_OK) {
                        dynamics.setPlayedPos(0);
                    } else {
                        dynamics.setPlayedPos(data.getIntExtra(SkipUtil.EX_POS, 0));
                    }
                }
            }
        }
    }

    /**
     * 跳转视频播放页面
     * @param item
     * @param position
     */
    private void playClick(ADynamicsItem item, int position) {
        SkipUtil.skipToVideoPlay(this, contentVideoUrl, item.getCurrentPos() * 1000, position);
    }

    //列表单元点击
    OnItemInternalClick playOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (floatVideoUtils != null && floatVideoUtils.isShowing()) {
                int currentPosition = 0;
//                        floatVideoUtils.getPlayerView().getCurrentPosition();
                dynamicsTemp = (ADynamicsItem) adapter.getItem(tempPos);
                dynamicsTemp.setCurrentPos(currentPosition / 1000);
            }
            ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
            contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
            playView = view;
            playClick(dynamics, position);
//            if (dynamics.getCurrentPos() != 0) {
//                playVideo(view, contentVideoUrl, dynamics.getDataTitle(), dynamics.getCurrentPos() * 1000);
////                floatVideoUtils.startPlay(dynamics.getCurrentPos() * 1000);
//            } else {
//                playVideo(view, contentVideoUrl, dynamics.getDataTitle(), 0);
//            }
            tempPos = position;
        }
    };

    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
        if (title_lay != null) {
            title_lay.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);
        if (title_lay != null) {
            title_lay.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(circle_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(circle_list, 1);
    }

}
